package com.wuchao.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author wuchao66
 * @Date 2022/6/27 15:21
 * @Version 1.0
 */
public class Util {
    private static SqlSessionFactory sf;//工厂
    static {//静态块
        //找出工人
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder
                = new SqlSessionFactoryBuilder();
        //工人根据全局配置文件也就是 xml 建立工厂，建完就死，工资都没得发
        //文件流读进来
        try {
            InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
          sf=  sqlSessionFactoryBuilder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //出产品
    public static SqlSession openSqlsession(){
       return sf.openSession(true);//默认不开事务
    }
    //杀掉sqlsession
    public static void closeSqlsession(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
